package com.duk.controller;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.duk.model.User;
import com.duk.service.LoginService;

@Controller
@RequestMapping(value = "/login")
public class LoginController
{
	@Resource
	private LoginService loginService;

	@RequestMapping(value = "/main")
	public String toLogin(HttpServletRequest req, HttpServletResponse resp)
	{
		List<Map<String, Object>> list = loginService.getData();
		String dh = JSON.toJSONString(list);
		req.setAttribute("dh", dh);
		return "/admin/main";
	}

	@RequestMapping(value = "/loginOut")
	@ResponseBody
	public int loginOut(HttpServletRequest req, HttpServletResponse resp) throws IOException
	{
		req.getSession().removeAttribute("userInSession1");
		return 1;
	}

	@RequestMapping(value = "/checkUser")
	@ResponseBody
	// 接收到前台传来的验证码字符串和账号密码
	public int checkUser(String verify, User user, HttpServletRequest req)
	{
		int i;
		// 通过request来获取session然后在session里面获取“checkcode”，也就是工具类生成的验证码字符串
		String str1 = (String) req.getSession().getAttribute("verify");
		// 利用字符串不区分大小写的方法看验证码是否输入正确
		if (str1.equalsIgnoreCase(verify))
		{
			// 如果验证码正确就会把User对象继续传到service层进行进一步的逻辑判断
			i = loginService.checkUser(user);
			if (i == 1)
			{
				req.getSession().setAttribute("userInSession", i);
				req.getSession().setAttribute("userInSession1", user.getUsername());
				return i;
			} else
			{
				return i;
			}
		} else
		{
			// 验证码错误
			return 3;
		}

	}

	/*
	 * @RequestMapping(value = "/checkcode")
	 * 
	 * @ResponseBody public int checkcode(String str, HttpServletRequest req) {
	 * String str1 = (String) req.getSession().getAttribute("checkcode"); if
	 * (str.equalsIgnoreCase(str1)) { return 1; } else { return 0; } }
	 */
}
